package com.example.votes.service;

import com.example.votes.entity.Image;
import com.example.votes.repository.ImageRepository;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class VoteService {

    // 改为注入专用的 logsJdbcTemplate
    private final JdbcTemplate logsJdbc;
    private final ImageRepository imageRepo;

    public VoteService(
            @Qualifier("logsJdbcTemplate") JdbcTemplate logsJdbc,
            ImageRepository imageRepo) {
        this.logsJdbc = logsJdbc;
        this.imageRepo = imageRepo;
    }

    public Map<String, String> vote(String username, String character, String time) {

        String select = "SELECT vote_num, vote_time FROM user_votes WHERE username = ?";
        List<Map<String, Object>> rows = logsJdbc.queryForList(select, username);

        int voteNum;
        if (rows.isEmpty()) {
            String ins = "INSERT INTO user_votes(username, vote_num, vote_time) VALUES(?, 3, ?)";
            logsJdbc.update(ins, username, time);
            voteNum = 3;
        } else {
            Map<String,Object> row = rows.get(0);
            voteNum = (Integer)row.get("vote_num");
            String voteTime = (String)row.get("vote_time");
            if (!time.equals(voteTime)) {
                String upd1 = "UPDATE user_votes SET vote_num = 3, vote_time = ? WHERE username = ?";
                logsJdbc.update(upd1, time, username);
                voteNum = 3;
            }
            if (voteNum <= 0) {
                return Map.of("success","false","msg","投票失败，今天投票数量已达上限！");
            }
            String dec = "UPDATE user_votes SET vote_num = vote_num - 1 WHERE username = ?";
            logsJdbc.update(dec, username);
        }

        Image img = imageRepo.findAllByOrderByVoteCountDesc()
                .stream()
                .filter(i->i.getImageName().equals(character))
                .findFirst()
                .orElseThrow(() -> new RuntimeException("角色不存在:"+character));
        img.setVoteCount(img.getVoteCount()+1);
        imageRepo.save(img);

        return Map.of("success","true","msg","投票成功！");
    }
}